<?php
namespace Wap\Controller;
use Think\Controller;
use Org\Util\Wechat;
use Wap\Controller\UsercenterController;

//import("ORG.Wechat");
//import("ORG.ChintOAuth");
/**
 * 用户入口检测试类
 */
class WapController extends UsercenterController{
    public $openid;	
    public $userinfo;
    public $ctoauth;
    public $weObj;
    public function _initialize() {
    	parent::_initialize();
    	\Think\Log::write('现进入 9亩 WapController');
    	// 表示项目是通过共同类进行网页授权获取用户信息
    	if(C('JOIN_COMMON_OAUTH')) {
    		\Think\Log::write("当前的9亩是 配置状态 公共授权跳转 ");
    		$openid_get = trim($_GET['loginUserId']);
    		// 如果url没有带上openid
    		if(empty($openid_get)) {
    			$openid = session('openid');
	    		if(!empty($openid)) {
	    			$openid = session('openid');
		    		$this->userinfo = M('wxuser')->where(array('openid' => $openid))->find();
	    		} else {
	    			\Think\Log::write("Re公共授权失败,重新回到公共授权类进行授权");
	    			$selfUrl = getSelfUrl();
	    			$oauthUrl = C('JOIN_COMMON_OAUTH_URL').$selfUrl;
	    			header("Location:$oauthUrl");
		    		exit;
	    		}
    		} else {
	    		if(!session('openid')) {
	    			// 查询是否点菜系统有无这个用户
	    			\Think\Log::write("session为空，需向CWPU请求微信用户数据");
	    			$user_model = M("wxuser");
			        $where = array('openid' => $openid_get);
			        $this->userinfo = $user_model->where($where)->find();
			        
			        \Think\Log::write('userinfo => ' . dump($this->userinfo, false));
			        // 数据库无用户信息，进行信息获取
			        if($this->userinfo == null) {
		            	$userinfoFromCPWU = httpPost(C('SERVER_URL').'/user/getByUserId', array('userId' => $openid_get));
		            	\Think\Log::write('CWPU获取用户信息 =》 '. dump($userinfoFromCPWU, false));
		            	if($userinfoFromCPWU->code == 200) {
			            	$newUser = array(
								'openid'			=> $openid_get,
								'nickname'			=> $userinfoFromCPWU->info->nickname,
								'city'				=> '',
								'province'			=> '',
								'headimgurl'		=> $userinfoFromCPWU->info->head,
								'subscribe_time'	=> time(),
								'status'			=> 1,	// 订阅状态
							);
							\Think\Log::write("将新用户数据插入9亩用户表");
							$result = M('wxuser')->add($newUser);
							if($result == true) {
								\Think\Log::write("成功插入", 'INFO');
							} else {
								\Think\Log::write("失败插入", 'INFO');
							}
		            	}
		            }
		    		session('openid', $openid_get);
	    		} 
    		}
    	} else {
	    	if(!session('openid')) {
		    	\Think\Log::write('无session-openid，发起授权');
	        	$selfUrl = getSelfUrl();
	        	\Think\Log::write('构建本身selfUrl => ' . $selfUrl);
	            $this->weObj = new Wechat();
	            $state = time();
	            $codeUrl = $this->weObj->getOauthRedirect($selfUrl, $state, 'snsapi_userinfo');
	            \Think\Log::write('codeUrl => ' . $codeUrl);
	            if(empty($_GET['code']) && empty($_GET['state'])) {
	            	\Think\Log::write('跳转到 codeurl');
		            header("Location:$codeUrl");
		            exit();
	            } 
	            \Think\Log::write('授权返回 Code = '.$_GET['code']);
	            $authResult = $this->weObj->getOauthAccessToken();
	            \Think\Log::write('authResult => ' . dump($authResult, false));
	            $openid = null;
	            if($authResult) {
		            $this->openid = $authResult['openid'];
		            \Think\Log::write('snsapi_base 获取到openid => ' . $openid);
		            // 数据库查询
		            $user_model = M("wxuser");
			        $where = array('openid' => $this->openid);
			        $this->userinfo = $user_model->where($where)->find();
			        	
			        \Think\Log::write('userinfo => ' . dump($this->userinfo, false));
			        // 数据库无用户信息，进行信息获取
			        if($this->userinfo == null) {
		            	$wxuserinfo = $this->weObj->getOauthUserinfo($authResult['access_token'], $this->openid);
		            	\Think\Log::write('网页获取用户信息 =》 '. dump($wxuserinfo, false));
		            	if($wxuserinfo) {
			            	$newUser = array(
								'openid'			=> $wxuserinfo['openid'],
								'nickname'			=> $wxuserinfo['nickname'],
								'city'				=> $wxuserinfo['city'],
								'province'			=> $wxuserinfo['province'],
								'headimgurl'		=> $wxuserinfo['headimgurl'],
								'subscribe_time'	=> time(),
								'status'			=> 1,	// 订阅状态
							);
							$result = M('wxuser')->add($newUser);
							if($result == true) {
								\Think\Log::write("成功插入", 'INFO');
							} else {
								\Think\Log::write("失败插入", 'INFO');
							}
		            	}
		            }
		            session('openid', $this->openid);
	            } else {
		            echo "九亩获取微信用户信息获取失败！";
		            exit();
	            }
	        }
	        $this->openid = session('openid');
	        
	        $where = array('openid' => $this->openid);
	        $this->userinfo = M("wxuser")->where($where)->find();
	        
	        \Think\Log::write('userinfo => ' . dump($this->userinfo, false));
	            
	        if(!$this->userinfo){
	            $this->error("用户出错，请关闭窗口后，重新链接");
	            exit();
	        }
    	}
    	$this->openid = session('openid');
        $this->assign("userinfo", $this->userinfo);
    }
    /*
    public function _initialize_bak() {
    	\Think\Log::write("Wap->initialize!");
    	if(!session('openid')) {
    		$selfUrl = getSelfUrl();
        \Think\Log::write('selfUrl => ' . $selfUrl);
        $this->ctoauth = new \Org\Util\ChintOAuth();
        $codeUrl = $this->ctoauth->getOauthRedirect($selfUrl);
        \Think\Log::write('codeUrl => ' . $codeUrl);
        if(empty($_GET['code']) && empty($_GET['state'])) {
         	\Think\Log::write('tiaozhuan codeurl');
          header("Location:$codeUrl");
          exit();
        } 
        \Think\Log::write('there is Code'.$_GET['code']);
        $authResult = $this->ctoauth->getOauthAccessToken($selfUrl);
        \Think\Log::write('ctoauth authResult => ' . dump($authResult, false));
        $openid = null;
        if($authResult) {
        	// 从ctoauth获取到用户信息
         	$wxuserinfo = $this->ctoauth->getOauthUserinfo($authResult['access_token']);
         	\Think\Log::write('userinfo from ctoauth => '. dump($wxuserinfo, false));
         	if($wxuserinfo) {
         		// 数据库无用户信息，进行信息获取
         		$this->openid = $wxuserinfo['userId'];
         		\Think\Log::write("数据库获取用户之前 this-openid =".$this->openid);
         		$where = array("openid" => $this->openid);
         		$this->userInfo = M("wxuser")->where($where)->find();
         		if($this->userInfo == null) {
         			$newUser = array(
			         'openid'          	 => $wxuserinfo['userId'],
			         'nickname'      	 => $wxuserinfo['nickname'],
			         'headimgurl'    	 => $wxuserinfo['headimgurl'],
			         'subscribe_time'  	 => time(),
			         'status'      		 => 1, // 订阅状态
			        );
	      			$result = M('wxuser')->add($newUser);
	      			if($result == true) {
	       				\Think\Log::write("insert into success", 'INFO');
			        } else {
			         	\Think\Log::write("insert into fail", 'INFO');
			        }
         		} 
         		session('openid', $this->openid);
         	} else {
         		$this->error("ChintOAuth认证出错！");
         		exit();
         	}
        } else {
        	header("Content-type: text/html; charset=utf-8"); 
          echo "用户信息获取失败！";
          exit();
        }
      }
      $this->openid = session('openid');
      $where = array('openid' => $this->openid);
      $this->userinfo = M("wxuser")->where($where)->find();
      $this->assign("openid", $this->openid);
      \Think\Log::write('userinfo => ' . dump($this->userinfo, false));
    }
    
    */
    public function initialize_old(){
      //session(null);
      //$this->redirect(GROUP_NAME.'/Auth/test');
      /*
      if(session('openid')){
		$user_model = M("wxuser");
          $where = array('openid'=>session('openid'));
          $this->userinfo = $user_model->where($where)->find();
          $this->openid = session('openid');
          \Think\Log::write('userinfo => ' . dump($this->userinfo, false));
          
          if(!$this->userinfo){
              $this->error("用户出错，请关闭窗口后，重新链接");
          }
      } else {
      */
      \Think\Log::write("user:".session('user'));
      \Think\Log::write("userId:".$_GET['userId'],"info");
      \Think\Log::write("openid:".session('openid'),"info");
      \Think\Log::write("session:".session_save_path(),"info");
      $openid = $_GET['userId'];
      if(!session('openid')) {
        \Think\Log::write("session-openid is null");
        $this->openid = $openid;
        if($openid == null){
          //header("Content-type: text/html; charset=utf-8"); 
          //echo "请登陆！";
          $this->error("用户数据错误，请重新登陆！");
          exit();
        }

        $user_model = M("wxuser");
        $where = array('openid' => $this->openid);
        $this->userinfo = $user_model->where($where)->find();
        \Think\Log::write('userinfo => ' . dump($this->userinfo, false));
        session('openid', $this->openid);
        if(!$this->userinfo){
          $msg = $this->httpGet(C('SERVER_URL')."/user/getByUserId?userId=".$openid);
          if($msg->code != 200){
            $this->error("错误用户Openid，请重新登陆！");
            exit();
          }
          $user = $msg->info;

          $newUser = array(
             'openid'            => $user->userId,
             'nickname'          => $user->nickname,
             'headimgurl'        => $user->headimgurl,
             'subscribe_time'    => time(),
             'status'            => 1,   // 订阅状态
          );
          \Think\Log::write('newUser => ' . dump($newUser, false));

          $result = M('wxuser')->add($newUser);

          session('openid', $this->openid);
        
          if($result == true) {
            \Think\Log::write("成功插入", 'INFO');
          } else {
            \Think\Log::write("失败插入", 'INFO');
          }
          $user_model = M("wxuser");
          $where = array('openid' => $this->openid);
          $this->userinfo = $user_model->where($where)->find();
          \Think\Log::write('userinfo => ' . dump($this->userinfo, false));
          if(!$this->userinfo){
              $this->error("用户出错，请关闭窗口后，重新链接");
              exit();
          }
        }
        $this->openid = session("openid");
        $this->assign("userinfo", $this->userinfo);
        $this->assign("openid", $this->openid);
      } else {
        $this->openid = session("openid");
        $this->assign("openid", $this->openid);
        \Think\Log::write('header:'.$_SERVER['HTTP_COOKIE'],'info');
      }
    }

    private function httpGet($url){
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);

        /* 新增代理部分 */
        if(C('CHINT_AGENT')) {
            $proxy = C('AGENT_URL');
            $proxyport = C('AGENT_PORT');
            curl_setopt($ch, CURLOPT_PROXY, $proxy);
            curl_setopt($ch, CURLOPT_PROXYPORT, $proxyport);
        }
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        \Think\Log::write('output:'.$output,'INFO');

        $responseBlock = explode("\r\n\r\n",$output);
        $response_body = $responseBlock[count($responseBlock)-1];

        \Think\Log::write('body:'.$response_body,'INFO');

        $msg = json_decode($response_body);
        return $msg;
    }
}